import 'reflect-metadata';

import logger from '../../common/logger';
import { configurationService } from '../../domain/service/configService';
import { Connection, createConnection, ConnectionOptions } from 'typeorm';
export class TypeORMService {
  private DEFAULT_CONNECTION_NAME = 'default';

  private _connection: Connection;

  public async init() {
    this._connection = await createConnection(this.ConfigurationObject);
    logger.info('Connection to pg server established');
  }

  public async disconnect() {
    await this._connection.close();
    logger.info('Disconnected from pq server');
  }

  public get connection() {
    return this._connection;
  }

  public get ConfigurationObject(): ConnectionOptions {
    const { db: { type, config }, typeorm } = configurationService.config;
    return {
      name: this.DEFAULT_CONNECTION_NAME,
      type: type as any,
      synchronize: typeorm.synchronize,
      database: config.database,
      entities: typeorm.entities,
      port: config.port,
      host: config.host,
      username: config.userName,
      password: config.password
    };
  }
}